package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.config.LoginUserSecurityDto;
import cd.cdyb.sms.dao.AdministratorsDao;
import cd.cdyb.sms.domain.Administrators;
import cd.cdyb.sms.domain.Employee;
import cd.cdyb.sms.dto.AccessTokenModel;
import cd.cdyb.sms.exception.BusinessException;
import cd.cdyb.sms.service.AdministratorsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Objects;

@Service("administratorsService")
@Slf4j
public class AdministratorsServiceImpl implements AdministratorsService {

    @Resource
    private AdministratorsDao administratorsDao;

    @Resource
    private RestTemplate restTemplate;

    @Value("${server.port}")
    private String port;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public LoginUserSecurityDto login(String username, String password) throws BusinessException {
        LambdaQueryWrapper<Administrators> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Administrators::getUsername, username);
        Administrators administrators = administratorsDao.selectOne(wrapper);
        if (Objects.isNull(administrators)) {
            throw new BusinessException("企业不存在");
        }
        log.info("用户[{}]登录,密码[{}]", username, password);

        LoginUserSecurityDto loginUserSecurityDto = new LoginUserSecurityDto();
        String accessToken = this.generateAccessToken("ADMIN@" + username, password);
        loginUserSecurityDto.setUsername(administrators.getUsername());
        loginUserSecurityDto.setId(administrators.getAdministratorsId());
        loginUserSecurityDto.setAccessToken(accessToken);
        return loginUserSecurityDto;
    }



    public String generateAccessToken(String username, String password) throws BusinessException {
        try {
            String uri = "http://127.0.0.1:" + port + contextPath + "/oauth/token?client_id=helpCenter&client_secret=123456&grant_type=password&username={username}&password={password}"
                    .replace("{username}", username)
                    .replace("{password}", password);
            URI resetPwdUri = new URIBuilder(uri).build();

            RequestEntity requestEntity = new RequestEntity(HttpMethod.POST, resetPwdUri);
            ResponseEntity<AccessTokenModel> responseEntity = restTemplate.exchange(requestEntity, AccessTokenModel.class);


            return responseEntity.getBody().getData().getAccessToken();
        } catch (RestClientResponseException e) {
            log.error("generateAccessToken RestClientResponseException error:", e);
            if (e.getResponseBodyAsString().contains("User is disabled")) {
                throw new BusinessException("error.visitor.usernameOrPasswordInvalid", "账号或密码错误!");
            } else {
                throw new BusinessException("error.visitor.usernameOrPasswordInvalid", "账号或密码错误!");
            }
        } catch (Exception e) {
            log.error("generateAccessToken other error:", e);
            throw new BusinessException("error.visitor.usernameOrPasswordInvalid", "账号或密码错误!");
        }
    }

}
